*** Settings ***
Documentation           SSH连接关键库
Resource                ../resource.robot
Library                 test_ssh_msg.py

*** Keywords ***
Try Connect SSH With Retry
    [Arguments]    ${host}    ${port}    ${username}    ${password}    ${retries}=3    ${retry_interval}=2s
    FOR    ${i}    IN RANGE    ${retries}
        ${ssh}=    Run Keyword And Ignore Error    Try Connect SSH    ${host}  ${port}  ${username}  ${password}
        Return From Keyword If    '${ssh[0]}' == 'PASS'    ${ssh[1]}
        Sleep    ${retry_interval}
    END
    Fail    SSH连接失败（重试${retries}次后仍失败）

Connect To BMC SSH
    ${ssh}=    Try Connect SSH With Retry    ${OPENUBMC_HOST}  ${SSH_PORT}  ${OPENUBMC_USERNAME}  ${OPENUBMC_PASSWORD}
    RETURN    ${ssh}

Execute SSH Command
    [Documentation]    执行SSH命令
    [Arguments]    ${ssh}    ${command}    ${timeout}=60
    ${rsp}=    Send Ssh Msg    ${ssh}    ${command}    ${timeout}
    # 如果检测到连接问题，自动重连一次
    IF    "SSH会话未激活" in """${rsp}""" or "SSH命令执行错误" in """${rsp}"""
        Log    检测到SSH连接问题，尝试重新连接    level=WARN
        ${new_ssh}=    Connect To BMC SSH
        Set Suite Variable    ${ssh}    ${new_ssh}
        ${rsp}=    Send Ssh Msg    ${ssh}    ${command}    ${timeout}
    END
    RETURN    ${rsp}

Close SSH Session
    [Documentation]    关闭SSH连接
    [Arguments]    ${ssh}
    Run Keyword And Ignore Error    Close SSH Connection    ${ssh}

Open SSH Connection
    [Documentation]    验证ssh连接是否正常
    ${ssh}=    Connect To BMC SSH
    Should Not Be Equal    ${ssh}    ${None}    msg=SSH连接失败
    Set Suite Variable    ${ssh}

Verify SSH Active
    [Arguments]    ${ssh}
    ${alive}=    Run Keyword And Return Status    Execute SSH Command    ${ssh}    echo 'ConnectionCheck'
    RETURN    ${alive}

Reconnect If Dead
    [Arguments]    ${ssh}
    ${is_alive}=    Verify SSH Active    ${ssh}
    Return From Keyword If    ${is_alive}    ${ssh}
    Log    连接已断开，尝试重新建立    level=WARN
    ${new_ssh}=    Connect To BMC SSH
    RETURN    ${new_ssh}

Verify SSH Connection
    [Arguments]    ${ssh}
    ${status}=    Run Keyword And Return Status    
    ...    Execute SSH Command    ${ssh}    echo ConnectionCheck
    Should Be True    ${status}    SSH连接已失效，需要重建连接